import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

interface SelectOption {
  label: string;
  value: string;
  disabled?: boolean;
}

/**
 * Select选择器组件
 * @element zss-select
 * @slot - 选项内容插槽
 */
@customElement('zss-select')
export class ZssSelect extends LitElement {
  static styles = css`
    :host {
      display: inline-block;
      position: relative;
      width: 100%;
    }
    
    .select-wrapper {
      position: relative;
      width: 100%;
    }
    
    .select-trigger {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      padding: 8px 30px 8px 12px;
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      background-color: var(--zss-bg-color);
      cursor: pointer;
      transition: border-color 0.2s, box-shadow 0.2s;
      font-size: var(--zss-font-size-base);
      color: var(--zss-text-color-regular);
    }
    
    .select-trigger:hover {
      border-color: var(--zss-border-color-hover);
    }
    
    .select-trigger:focus {
      border-color: var(--zss-color-primary);
      box-shadow: 0 0 0 2px var(--zss-color-primary-light-8);
    }
    
    .select-trigger.disabled {
      background-color: var(--zss-fill-color-light);
      border-color: var(--zss-border-color);
      color: var(--zss-text-color-disabled);
      cursor: not-allowed;
    }
    
    .select-trigger.disabled:hover {
      border-color: var(--zss-border-color);
    }
    
    .dropdown-icon {
      transition: transform 0.2s;
      color: var(--zss-text-color-placeholder);
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
    }
    
    .dropdown-icon.open {
      transform: translateY(-50%) rotate(180deg);
    }
    
    .dropdown-menu {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: var(--zss-bg-color);
      border: 1px solid var(--zss-border-color-light);
      border-radius: var(--zss-border-radius-base);
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 2000;
      max-height: 200px;
      overflow-y: auto;
      margin-top: 4px;
    }
    
    .option {
      padding: 8px 12px;
      cursor: pointer;
      transition: background-color 0.2s;
      font-size: var(--zss-font-size-base);
      color: var(--zss-text-color-regular);
    }
    
    .option:hover {
      background-color: var(--zss-fill-color-light);
    }
    
    .option.selected {
      background-color: var(--zss-color-primary-light-9);
      color: var(--zss-color-primary);
    }
    
    .option.disabled {
      color: var(--zss-text-color-disabled);
      cursor: not-allowed;
    }
    
    .option.disabled:hover {
      background-color: transparent;
    }

    /* 尺寸样式 */
    .select--small .select-trigger {
      padding: 6px 26px 6px 10px;
      font-size: var(--zss-font-size-extra-small);
    }

    .select--small .dropdown-icon {
      right: 6px;
    }

    .select--large .select-trigger {
      padding: 12px 34px 12px 14px;
      font-size: var(--zss-font-size-medium);
    }

    .select--large .dropdown-icon {
      right: 10px;
    }
  `;

  /**
   * 选择器值
   * @attr value
   */
  @property({ type: [String, Array] })
  value: string | string[] = '';

  /**
   * 占位符文本
   * @attr placeholder
   */
  @property({ type: String })
  placeholder = '请选择';

  /**
   * 是否禁用
   * @attr disabled
   */
  @property({ type: Boolean })
  disabled = false;

  /**
   * 是否可清空
   * @attr clearable
   */
  @property({ type: Boolean })
  clearable = false;

  /**
   * 是否多选
   * @attr multiple
   */
  @property({ type: Boolean })
  multiple = false;

  /**
   * 尺寸
   * @attr size
   */
  @property({ type: String })
  size: 'small' | 'default' | 'large' = 'default';

  /**
   * 选项数据
   */
  @property({ type: Array })
  options: SelectOption[] = [];

  /**
   * 是否展开下拉菜单
   */
  @state()
  private isOpen = false;

  private handleTriggerClick() {
    if (!this.disabled) {
      this.isOpen = !this.isOpen;
    }
  }

  private handleClearClick(e: Event) {
    e.stopPropagation();
    if (this.multiple) {
      this.value = [];
    } else {
      this.value = '';
    }
    this.dispatchEvent(new CustomEvent('change', { 
      detail: { value: this.value } 
    }));
  }

  private handleOptionClick(option: SelectOption) {
    if (!option.disabled) {
      if (this.multiple) {
        const currentValue = Array.isArray(this.value) ? [...this.value] : [];
        const index = currentValue.indexOf(option.value);
        
        if (index > -1) {
          currentValue.splice(index, 1);
        } else {
          currentValue.push(option.value);
        }
        
        this.value = currentValue;
      } else {
        this.value = option.value;
        this.isOpen = false;
      }
      
      this.dispatchEvent(new CustomEvent('change', { 
        detail: { value: this.value } 
      }));
    }
  }

  private handleTagClose(value: string, e: Event) {
    e.stopPropagation();
    if (this.multiple && Array.isArray(this.value)) {
      const newValue = this.value.filter(v => v !== value);
      this.value = newValue;
      this.dispatchEvent(new CustomEvent('change', { 
        detail: { value: this.value } 
      }));
    }
  }

  private handleDocumentClick = (e: Event) => {
    if (!this.contains(e.target as Node)) {
      this.isOpen = false;
    }
  };

  connectedCallback() {
    super.connectedCallback();
    document.addEventListener('click', this.handleDocumentClick);
  }

  disconnectedCallback() {
    document.removeEventListener('click', this.handleDocumentClick);
    super.disconnectedCallback();
  }

  private getSelectedLabel() {
    if (this.multiple && Array.isArray(this.value)) {
      if (this.value.length === 0) {
        return this.placeholder;
      }
      
      const selectedLabels = this.value.map(value => {
        const option = this.options.find(opt => opt.value === value);
        return option?.label || value;
      });
      
      return selectedLabels.join(', ');
    } else {
      const value = this.value as string;
      if (!value) {
        return this.placeholder;
      }
      
      const option = this.options.find(opt => opt.value === value);
      return option?.label || value;
    }
  }

  render() {
    const wrapperClasses = [
      'select-wrapper',
      this.size !== 'default' ? `select--${this.size}` : ''
    ].filter(Boolean).join(' ');

    const hasValue = this.multiple ? 
      Array.isArray(this.value) && this.value.length > 0 : 
      !!this.value;

    return html`
      <div class=${wrapperClasses}>
        <div 
          class="select-trigger ${this.disabled ? 'disabled' : ''}"
          @click=${this.handleTriggerClick}
        >
          ${this.multiple && Array.isArray(this.value) && this.value.length > 0 ? html`
            <div style="display: flex; flex-wrap: wrap; gap: 4px; flex: 1;">
              ${this.value.map(value => {
                const option = this.options.find(opt => opt.value === value);
                const label = option?.label || value;
                return html`
                  <span style="
                    display: inline-flex;
                    align-items: center;
                    background: var(--zss-color-primary-light-9);
                    color: var(--zss-color-primary);
                    padding: 0 8px;
                    border-radius: var(--zss-border-radius-base);
                    font-size: var(--zss-font-size-extra-small);
                  ">
                    ${label}
                    <span 
                      style="margin-left: 4px; cursor: pointer;"
                      @click=${(e: Event) => this.handleTagClose(value, e)}
                    >
                      ×
                    </span>
                  </span>
                `;
              })}
            </div>
          ` : html`
            <span>${this.getSelectedLabel()}</span>
          `}
          
          <div style="display: flex; align-items: center;">
            ${this.clearable && hasValue ? html`
              <span 
                style="margin-right: 8px; cursor: pointer; color: var(--zss-text-color-placeholder);"
                @click=${this.handleClearClick}
              >
                ×
              </span>
            ` : ''}
            <span class="dropdown-icon ${this.isOpen ? 'open' : ''}">▼</span>
          </div>
        </div>
        
        ${this.isOpen ? html`
          <div class="dropdown-menu">
            ${this.options.map(option => {
              const isSelected = this.multiple ? 
                Array.isArray(this.value) && this.value.includes(option.value) :
                this.value === option.value;
              
              return html`
                <div 
                  class="option ${isSelected ? 'selected' : ''} ${option.disabled ? 'disabled' : ''}"
                  @click=${() => this.handleOptionClick(option)}
                >
                  ${option.label}
                </div>
              `;
            })}
          </div>
        ` : ''}
      </div>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-select': ZssSelect;
  }
}